import random
import time
# import threading
import multiprocessing

# flipAgain = 'yes'
# lock = multiprocessing.Lock()
# processes = []
# # global TOTALHEADS
# TOTALHEADS = 0
# # global TOTALTAILS
# TOTALTAILS = 0
# #logFile = open('./flip_log.txt', 'w')
# #logFile.write('Heads, Tails, Difference \n')

def coinflip(jobcount, q):
    instancerandom = random.Random()
    flipcount = 0
    flipheads = 0
    fliptails = 0
    # global TOTALHEADS
    # global TOTALTAILS
    print('Starting a process with ' + str(jobcount))

    while flipcount < jobcount:
        flipvalue = instancerandom.randint(0, 1)

        if flipvalue == 1:
            flipheads += 1
        else:
            fliptails += 1

        flipcount += 1

#        logFile.write(str(flipheads) + ', ' + str(fliptails) + ', ' + str(flipheads - fliptails)+ '\n')

    if flipcount == jobcount:
        q.put([flipheads, fliptails])

    return

if __name__ == '__main__':
    q = multiprocessing.Queue()
    flipAgain = 'yes'
    lock = multiprocessing.Lock()
    processes = []
    # global TOTALHEADS
    TOTALHEADS = 0
    # global TOTALTAILS
    TOTALTAILS = 0

    while flipAgain == 'yes' or flipAgain == 'y':

        print('Welcome to Flip Count!')
        print('How many times would you like me to flip?')
        flipInput = int(input())
        print('Define the number of cores available to your system.')
        coreInput = int(input())
        # if coreInput == 1:
        #     pass
        # else:
        #     coreInput -= 1
        REMAINDER = (flipInput % coreInput)
        JOBCOUNT = (flipInput // coreInput)
        startTime = time.clock()

        for i in range(coreInput):
            if i == 0:
                t = multiprocessing.Process(target=coinflip, args=((JOBCOUNT + REMAINDER),q,))
                processes.append(t)
                t.start()
            else:
                t = multiprocessing.Process(target=coinflip, args=(JOBCOUNT,q,))
                processes.append(t)
                t.start()
        for i in processes:
            print(i)
            i.join()

        while q.empty() == False:
            qResults = q.get()
            processHeads = qResults[0]
            processTails = qResults[1]
            TOTALHEADS += processHeads
            TOTALTAILS += processTails

        processTime = time.clock() - startTime
        print('Elapsed time ' + str(processTime) + 's')
        print('Your totals were ' + str(TOTALHEADS) + ' Heads and ' + str(
            TOTALTAILS) + ' Tails with a total difference of ' + str(TOTALHEADS - TOTALTAILS) + '.')
        print('Would you like to flip again?')
        flipAgain = str(input())

    #logFile.close()
